﻿using System;
using Hammock;
using Hammock.Authentication.OAuth;
using WeiboPlus.Models;
using WeiboPlus.Service;

namespace WeiboPlus.Service
{
    public abstract class OAuthServiceBase : SNSServiceBase<SNSAccount>, IOAuthService
    {
        public virtual void RequestToken(Action<SNSAccount, SNSResult> action)
        {
           //string authUrl = string.Format("{0}{1}?client_id={2}&response_type=code&redirect_uri={3}&display=mobile", Provider.AuthSettings.CLIENT, Provider.AuthSettings.PATH_AUTHORIZE, Provider.AuthSettings.CONSUMER_KEY, Provider.AuthSettings.CALLBACK_URL);
           // Account.AuthorizeURL = authUrl;
           // action(Account, new SNSResult() { IsSuccess = true, Message = "Require Request Token Success" });
            var client = CreateRestClient();

            var request = new RestRequest
            {
                Credentials = CreateCredentials(OAuthType.RequestToken),
                Path = Provider.AuthSettings.PATH_REQUEST_TOKEN
            };

            Execute(res =>
            {
                var oAuthToken = GetQueryParameter(res.Content, "oauth_token");
                var oAuthTokenSecret = GetQueryParameter(res.Content, "oauth_token_secret");

                if (String.IsNullOrEmpty(oAuthToken) || String.IsNullOrEmpty(oAuthTokenSecret))
                {
                    //throw new Exception("error occured when retrieving oauth token");
                    if (action != null)
                        action(Account, new SNSResult() { IsSuccess = true, Message = "授权过程中产生错误，请稍候再试！" });
                }

                Account.AuthorizeURL = Provider.AuthSettings.CLIENT + Provider.AuthSettings.PATH_AUTHORIZE + "?oauth_token=" + oAuthToken;
                Account.OAuthToken = oAuthToken;
                Account.OAuthTokenSecret = oAuthTokenSecret;

                if (action != null)
                    action(Account, new SNSResult() { IsSuccess = true, Message = "Require Request Token Success" });
            }, request);
        }

        public virtual void AccessToken(Action<SNSAccount, SNSResult> action)
        {
            var client = CreateRestClient();

            var request = new RestRequest
            {
                Credentials = CreateCredentials(OAuthType.AccessToken),
                Path = Provider.AuthSettings.PATH_ACCESS_TOKEN
            };

            Execute(res =>
            {
                var accessToken = GetQueryParameter(res.Content, "oauth_token");
                var accessTokenSecret = GetQueryParameter(res.Content, "oauth_token_secret");

                if (String.IsNullOrEmpty(accessToken) || String.IsNullOrEmpty(accessTokenSecret))
                {
                    //throw new Exception("error occured when retrieving access token");
                    if (action != null)
                        action(Account, new SNSResult() { IsSuccess = true, Message = "授权过程中产生错误，请稍候再试！" });
                }
                Account.AccessToken = accessToken;
                Account.AccessTokenSecret = accessTokenSecret;
                Account.IsBind = true;
                //account.IsAuthorized = true;

                if (action != null)
                    action(Account, new SNSResult() { IsSuccess = true, Message = "Require Access Token Success" });
            }, request);
        }

        protected string GetQueryParameter(string input, string parameterName)
        {
            foreach (string item in input.Split('&'))
            {
                var parts = item.Split('=');
                if (parts[0] == parameterName)
                {
                    return parts[1];
                }
            }
            return String.Empty;
        }

        public virtual void AccessTokenRefresh(Action<SNSAccount,SNSResult> action)
        {

        }

    }
}
